package topcoder;

public class CountingSeries {

	public long countThem(long a, long b, long c, long d, long upperBound){
		long x = (int) Math.floor((upperBound - a) / b)+1;
		long y;
		if(d!=1)
			y = (int) Math.floor(Math.log(upperBound / c) / Math.log(d))+1;
		else if(c*Math.pow(d, 0) > upperBound)
			y=1;
		else
			y=0;
		
		long both = 0;
		long start = 0;
		double first, second;
		loop:
			for(long i=0; i<y; i++){
				for(long j=start; j<x; j++){
					first = a+b*j;
					second = c*Math.pow(d, i);
					if(first > second){
						start = j+1;
						continue loop;
					}
					else if(first == second){
						start = j+1;
						both++;
						continue loop;
					}
				}
			}
		return x+y-both;
	}
	
	public static void main(String[] args) {
		CountingSeries cs = new CountingSeries();
		cs.countThem(720176314585l, 488693376359l, 514776939786l, 38245, 382227406106l);
	}
}
